﻿using Sustainalytics.Claims;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web.Http;
using Sustainalytics.Entities;

namespace Sustainalytics.News.Service.Utility
{
    public static class NewsClaimsCheckerExtensions
    {
        public static bool ValidateClaim(this IClaimsChecker claimsChecker, ApiController controller)
        {
            List<string> shortNames = new List<string>() { "client" };

            foreach (var sn in shortNames)
            {
                if (claimsChecker.Validate(controller, new List<Entities.ResourceParameters>() { new ResourceParameters { Key = "shortName", Value = sn.ToLowerInvariant() } }))
                    return true;
            }

            return false;
        }

        public static bool ValidateAdminClaim(this IClaimsChecker claimsChecker, ApiController controller)
        {
            List<string> shortNames = new List<string>() { "admin" };

            foreach (var sn in shortNames)
            {
                if (claimsChecker.Validate(controller, new List<Entities.ResourceParameters>() { new ResourceParameters { Key = "shortName", Value = sn.ToLowerInvariant() } }))
                    return true;
            }

            return false;
        }
       
        public static bool Validate(this IClaimsChecker claimsChecker, ApiController ctrl, List<ResourceParameters> parameters)
        {
            // get current principal
            var principal = (ClaimsPrincipal)ctrl.User;

            // get route prefix
            object[] attrs = ctrl.GetType().GetCustomAttributes(typeof(RoutePrefixAttribute), false);
            RoutePrefixAttribute routePrefixAttrs = attrs == null || attrs.Length == 0 ? null : attrs.Select(a => (RoutePrefixAttribute)a).FirstOrDefault();

            // get HTTP Method
            string httpMethod = ctrl.Request.Method.Method;

            bool valid = claimsChecker.Validate(
                claimsPrincipal: principal,
                resource: routePrefixAttrs == null ? null : routePrefixAttrs.Prefix,
                verb: httpMethod,
                parameters: parameters);

            return valid;
        }
    }
}
